package cn.edu.sctu.sctu_lysd.view.act;

import android.animation.ValueAnimator;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Toast;

import java.io.IOException;
import java.text.ParseException;
import java.util.List;

import cn.edu.sctu.sctu_lysd.R;
import cn.edu.sctu.sctu_lysd.alipay.PayActivity;
import cn.edu.sctu.sctu_lysd.base.BaseActivity;
import cn.edu.sctu.sctu_lysd.bean.ParcelMessageBean;
import cn.edu.sctu.sctu_lysd.biz.SubmitReleaseBiz;
import cn.edu.sctu.sctu_lysd.databinding.ActivitySubmitReleaseBinding;
import cn.edu.sctu.sctu_lysd.my_view.CustomDialog;
import cn.edu.sctu.sctu_lysd.my_view.DateChooseWheelViewDialog;
import cn.edu.sctu.sctu_lysd.presenter.SubmitReleasePresenter;
import cn.edu.sctu.sctu_lysd.utils.DateUtils;
import cn.edu.sctu.sctu_lysd.utils.ImageLoader;
import cn.edu.sctu.sctu_lysd.utils.JumpUtils;
import cn.edu.sctu.sctu_lysd.utils.L;
import cn.edu.sctu.sctu_lysd.utils.ProgressUtil;
import cn.edu.sctu.sctu_lysd.utils.ScreenUtils;
import cn.edu.sctu.sctu_lysd.utils.SharePreferenceUtils;

/**
 * Created by wangfuxin on 2017-04-09.
 */

public class SubmitReleaseAct extends BaseActivity implements SubmitReleaseBiz.SubmitReleaseView{

    private ActivitySubmitReleaseBinding binding;

    private String mStartTime = "";

    private String mEndTime = "";

    private final int START_TIME_FLAG = 0;
    private final int END_TIME_FLAG = 1;

    private SubmitReleaseBiz.Presenter mPresenter;

    private ParcelMessageBean parcelMessageBean;

    private static final int REQUEST_CODE_GOOD_MESSAGE = 1;
    private static final int REQUEST_CODE_ADDRESS = 2;

    private String parcelName = "";
    private String parcelWeight = "";
    private String parcelDescribe = "";
    private String imgPath = "";
    private List<String> parcelPhotnPath;


    private String receiverName = "";//收件人姓名
    private String receiverPhone = "";//收件人电话
    private String destinationDetail = "";//收件人详细地址

    private String originPre;//起始点
    private String originDetail;//起始点 详细
    private String destinationPre;//终点地址

    private ProgressUtil progressUtil;
    private ProgressDialog progressDialog;

    private PopupWindow demandPopupWindow = null;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_submit_release;
    }

    @Override
    protected void initAfter(Object bind) {

        binding = (ActivitySubmitReleaseBinding) bind;

        progressUtil = ProgressUtil.getInstance(this);

        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        getIntentData();

        binding.startTimeTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickTime(START_TIME_FLAG);
            }
        });


        binding.harvestAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SubmitReleaseAct.this, HarvestAddressAct.class);
                startActivityForResult(intent, REQUEST_CODE_ADDRESS);
            }
        });

        binding.goodsMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(SubmitReleaseAct.this, GoodsMessageAct.class);
                startActivityForResult(intent, REQUEST_CODE_GOOD_MESSAGE);
            }
        });

        binding.endTimeTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pickTime(END_TIME_FLAG);
            }
        });

        binding.releaseSubmitBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                try {

                    combinationData();

                    lightOff();

                    showPopWin(binding.endTimeTxt);

                } catch (ParseException e) {

                    Toast.makeText(SubmitReleaseAct.this, "信息填写不完整，请检查  ParseException", Toast.LENGTH_LONG).show();

                    e.printStackTrace();
                } catch (ParcelMessageError parcelMessageError) {

                    Toast.makeText(SubmitReleaseAct.this, "信息填写不完整，请检查  parcelMessageError", Toast.LENGTH_LONG).show();

                    parcelMessageError.printStackTrace();
                }

            }
        });

    }

    private void getIntentData() {

        Bundle extras = getIntent().getExtras();

        originPre = extras.getString(IndexActivity.ORIGIN_PRE);
        originDetail = extras.getString(IndexActivity.ORIGIN_DETAIL);


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_CODE_GOOD_MESSAGE && resultCode == RESULT_OK) {

            parcelName = data.getExtras().getString(GoodsMessageAct.NAME);

            parcelWeight = data.getExtras().getString(GoodsMessageAct.WEIGHT);

            parcelDescribe = data.getExtras().getString(GoodsMessageAct.DESCRIBE);

            imgPath = data.getExtras().getString(GoodsMessageAct.IMG_PATH);


            binding.parcelName.setText(parcelName);
            binding.parcelWeight.setText(parcelWeight);
            binding.parcelDescription.setText(parcelDescribe);

            ImageLoader.getInstance().loadImage(imgPath,binding.goodsImg,false);

        }


        if (requestCode == REQUEST_CODE_ADDRESS && resultCode == RESULT_OK) {

            receiverName = data.getExtras().getString(HarvestAddressAct.RECEIVER_NAME);

            receiverPhone = data.getExtras().getString(HarvestAddressAct.RECEIVER_PHONE);

            destinationPre = data.getExtras().getString(HarvestAddressAct.DESTINATION_PRE);

            destinationDetail = data.getExtras().getString(HarvestAddressAct.DESTINATION_DETAIL);


            L.e("receiverName",receiverName);


        }


    }

    private void combinationData() throws ParseException, ParcelMessageError {

        parcelMessageBean = new ParcelMessageBean();

        parcelMessageBean.setStartTime(DateUtils.strToDate(mStartTime, DateUtils.DATE_SDF));
        parcelMessageBean.setEndTime(DateUtils.strToDate(mEndTime, DateUtils.DATE_SDF));

        /**
         * 信息 不全 抛出异常
         */
        if (parcelName.equals("")) throw new ParcelMessageError("货物信息不全");
        if (parcelWeight.equals("")) throw new ParcelMessageError("货物信息不全");
        if (parcelDescribe.equals("")) throw new ParcelMessageError("货物信息不全");
        if (receiverName.equals("")) throw new ParcelMessageError("货物信息不全");
        if (receiverPhone.equals("")) throw new ParcelMessageError("货物信息不全");
        if (destinationPre.equals("")) throw new ParcelMessageError("货物信息不全");
        if (destinationDetail.equals("")) throw new ParcelMessageError("货物信息不全");

        parcelMessageBean.setName(parcelName);
        parcelMessageBean.setWeight(parcelWeight);
        parcelMessageBean.setDescription(parcelDescribe);
        parcelMessageBean.setFilePath(imgPath);

        parcelMessageBean.setReceiverName(receiverName);
        parcelMessageBean.setReceiverPhone(receiverPhone);

        parcelMessageBean.setDestinationPre(destinationPre);
        parcelMessageBean.setDestinationDetail(destinationDetail);

        parcelMessageBean.setOriginPre(originPre);
        parcelMessageBean.setOriginDetail(originDetail);


    }

    @Override
    protected void onResume() {
        super.onResume();
        initPresenter(new SubmitReleasePresenter(this, this));
        mPresenter.start();
    }

    @Override
    public void initPresenter(SubmitReleaseBiz.Presenter presenter) {

        this.mPresenter = presenter;


    }

    @Override
    public void uploadSuccess(long orderId) {

        progressUtil.dismiss(progressDialog);

        if (demandPopupWindow != null) {

            if (demandPopupWindow.isShowing()) {
                demandPopupWindow.dismiss();
            }
        }


        showAlertDialog(orderId);

    }

    public void showAlertDialog(final long orderId) {

        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        builder.setMessage("您已上传成功，点击确认立即支付");
        builder.setTitle("确认支付");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                Bundle bundle = new Bundle();
                bundle.putLong(PayActivity.ORDER_ID_INTENT_TAG,orderId);

                JumpUtils.jumpActivity(SubmitReleaseAct.this,PayActivity.class,bundle);

            }
        });

        builder.setNegativeButton("取消",
                new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        JumpUtils.jumpActivity(SubmitReleaseAct.this,IndexActivity.class);
                    }
                });
        builder.create().show();
    }

    @Override
    public void uploadFailed() {

        progressUtil.dismiss(progressDialog);

        Toast.makeText(this, "网络错误请重试", Toast.LENGTH_SHORT).show();

    }

    @Override
    public void showSelectPhoto(String[] path) {

    }

    public void pickTime(final int flag) {
        DateChooseWheelViewDialog startDateChooseDialog = new DateChooseWheelViewDialog(this,
                new DateChooseWheelViewDialog.DateChooseInterface() {
                    @Override
                    public void getDateTime(String time, boolean longTimeChecked) {
                        switch (flag) {

                            case START_TIME_FLAG:

                                mStartTime = time;

                                binding.startTimeTxt.setText(time);

                                break;

                            case END_TIME_FLAG:

                                mEndTime = time;

                                binding.endTimeTxt.setText(time);

                                break;
                            default:

                                break;

                        }

                    }
                });

        startDateChooseDialog.setDismissListener(new DateChooseWheelViewDialog.DismissListener() {
            @Override
            public void onDismiss() {

            }
        });
        startDateChooseDialog.showDateChooseDialog();
    }

    private void showPopWin(View view) {
        View contentView = null;
        Button button;
        final EditText priceDdit;

        if (contentView == null) {

            contentView = LayoutInflater.from(this).inflate(R.layout.pup_win_price, null);

            demandPopupWindow = new PopupWindow(contentView,
                    LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
            demandPopupWindow.setTouchable(true);
            demandPopupWindow.setTouchInterceptor(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    return false;
                }
            });
            demandPopupWindow.setWidth(ScreenUtils.getScreenWidth(this));
            demandPopupWindow.setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);

            ColorDrawable dw = new ColorDrawable(0xff0000);
            demandPopupWindow.setBackgroundDrawable(dw);
            demandPopupWindow.showAsDropDown(view, 0, 0);

            demandPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    lightOn();
                }
            });

            button = (Button) contentView.findViewById(R.id.btn);
            priceDdit = (EditText) contentView.findViewById(R.id.price_edit);

            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    String price = mPresenter.getInputSting(priceDdit);

                    if (!price.equals("")) {

                        progressDialog = progressUtil.getProgressDialog(ProgressDialog.STYLE_HORIZONTAL, true, "ssss");

                        progressDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                mPresenter.cancel();
                            }
                        });

                        parcelMessageBean.setTotalAmount(price);

                        try {

                            mPresenter.uploadMessage(parcelMessageBean);

                        } catch (IOException e) {
                            uploadFailed();
                        }

                    } else {

                        Toast.makeText(SubmitReleaseAct.this, "请填写价格", Toast.LENGTH_SHORT).show();
                    }

                }
            });
        }


    }


    /**
     * 内容区域变亮
     */
    private void lightOn() {
        final WindowManager.LayoutParams lp = this.getWindow().getAttributes();

        /**
         * 值动画
         */
        ValueAnimator valueAnimator = new ValueAnimator().ofFloat(0.3f, 1.0f);
        valueAnimator.setDuration(1000);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                lp.alpha = (float) animation.getAnimatedValue();
                SubmitReleaseAct.this.getWindow().setAttributes(lp);
            }
        });

        valueAnimator.start();
    }

    /**
     * 内容区域变暗
     */
    private void lightOff() {

        final WindowManager.LayoutParams lp = this.getWindow().getAttributes();

        /**
         * 值动画
         */
        ValueAnimator valueAnimator = new ValueAnimator().ofFloat(1.0f, 0.3f);
        valueAnimator.setDuration(500);
        valueAnimator.setInterpolator(new LinearInterpolator());
        valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                lp.alpha = (float) animation.getAnimatedValue();
                SubmitReleaseAct.this.getWindow().setAttributes(lp);
            }
        });

        valueAnimator.start();

        this.getWindow().setAttributes(lp);
    }

    class ParcelMessageError extends Exception {

        public ParcelMessageError(String message) {
            super(message);
        }
    }

}
